<template>
  <view class="cart">
    <!-- 当我们看到页面无从下手的时候 可以根据事件进行划分 -->
    <!-- 购物车头部 -->
    <view class="cart-top" @tap="chooseAddress">
      <block v-if="address.userName">
        <!-- 收货人 -->
        <view class="cart-top-content">
          <view class="cart-consignee">收货人：{{address.userName}}</view>
          <view class="cart-phone">{{address.telNumber}}</view>
        </view>
        <!-- 收货地址 -->
        <view class="address">收货地址：{{address.userAddress}}</view>
      </block>
      <block v-else>
        <view class="addConsignee">新增收件人</view>
      </block>
    </view>
    <!-- 购物车内容 -->
    <view class="cart-content">
      <!-- 购物车标题 -->
      <view class="cart-content-title">
        <span>图标</span>
        优购生活馆
      </view>
      <block v-for="(item,index) in cartList" :key="index">
        <!-- 购物车item -->
        <view @tap="gogogo(index)" class="cart-content-item">
          <!-- 单选框 -->
          <view class="item-change">
            <!-- 这个index是我们对象的键 相当于我们数组的索引 -->
            <span
              @tap.stop="singleChange(index)"
              class="iconfont icon-xuanze"
              :class="{'icon-xuanze-fill':item.state}"
            ></span>
          </view>
          <view class="item-content">
            <!-- 商品图片 -->
            <view class="item-img">
              <img :src="item.goods_small_logo" alt>
            </view>
            <!-- item描述 -->
            <view class="item-desc">
              <view>{{item.goods_name}}</view>
              <view>
                <view class="item-price">￥{{item.goods_price}}</view>
                <view>
                  <span @tap.stop="count(1,index)" class="addCount">+</span>
                  <span class="count">{{item.count}}</span>
                  <span @tap.stop="count(-1,index)" class="addCount">-</span>
                </view>
              </view>
            </view>
          </view>
        </view>
      </block>
    </view>
    <!-- 底部栏 -->
    <view class="cart-footer">
      <!-- 全选按钮 -->
      <view class="cart-allChange">
        <span
          @tap="allChange(allCount==cartLength)"
          class="iconfont icon-xuanze"
          :class="{'icon-xuanze-fill':allCount==cartLength}"
        ></span>
        全选
      </view>
      <!-- 总价 -->
      <view class="cart-allPrice">
        <view class="count-allPrice">
          合计：
          <span>￥{{allPrice}}</span>
        </view>
        <view class="sportPrice">包含运费</view>
      </view>
      <!-- 生成订单 -->
      <view @tap="auth" class="cart-pay">结算({{allCount}})</view>
    </view>
  </view>
</template>

<script>
import { orderCreate } from '@/api'
export default {
  data() {
    return {
      address: {
        userName: '',
        telNumber: '',
        userAddress: ''
      },
      cartList: {

      },
      allCount: 0,
      cartLength: 0//记录我对象的键的个数 相当于获取了对象有多少个值
    }
  },
  methods: {
    //获取收货人信息
    chooseAddress() {
      console.log(123)
      //微信api中提供了添加收件人信息的的事件在开放接口
      wx.chooseAddress({
        success: (res) => {
          //收件人名字
          this.address.userName = res.userName
          //号码
          this.address.telNumber = res.telNumber
          //具体地址 可以拼接字符串凑成完整的地址
          this.address.userAddress = res.provinceName + res.provinceName + res.cityName + res.countyName
          console.log(this.address)
          /* 将我们添加的收件人 存储到本地 我们以后进来可以获取我们之前增加的收件人 */
          wx.setStorageSync('address', this.address)
        }
      })
    },
    //方便调试的跳转
    gogogo(index) {
      wx.navigateTo({ url: `/pages/good_detail/main?goods_id=${index}` });
    },
    //单选按钮的选择
    singleChange(index) {
      this.cartList[index].state = !this.cartList[index].state
/*       wx.removeStorageSync('carts')
      wx.setStorageSync('key','data') */
    },
    //商品全选按钮状态改变事件
    allChange(allState) {
      console.log(allState)
      //将全选的去反按钮给我的所有单选按钮 
      for (let key in this.cartList) {
        this.cartList[key].state = !allState
      }
    },
    //添加商品的数量使用+号
    //减少商品的数量 - 在我们选择到0的时候还应该弹窗提示用户是否删除
    count(number, index) {

      this.cartList[index].count += number
      console.log(this.cartList[index].count)
      //当我们的商品数量减少的时候 较少到等于0 我们可以提示用户是否删除
      if (this.cartList[index].count < 1) {
        //使用微信api的界面 的showModal模态对话框来提示用户
        wx.showModal({
          title: '提示',
          content: '是否删除商品',
          showCancel: true, //是否显示取消按钮,
          confirmText: '删除', //确定按钮的文字，默认为取消，最多 4 个字符,
          confirmColor: '#f00', //确定按钮的文字颜色,
          success: (res) => {
            if (res.confirm) {
              console.log('用户点击确定')
              //点击确定我们就将我们的数据删除 通过delete可以删除对象的属性
              delete this.cartList[index]
              //我们在这为什么加这一步是因为我们的数据不能驱动视图更新 加了这个就行 给this.cartList换成一个新的对象
              // this.cartList = JSON.parse(JSON.stringify(this.cartList))
              //也可以直接删除我们的本地存储
              wx.setStorageSync('carts', this.cartList)
              this.cartList = wx.getStorageSync('carts');
            } else if (res.cancel) {
              console.log('用户点击取消')
              //当我们选择取消应该让我们的商品数量为1
              this.cartList[index].count = 1
            }
          }
        })
      }
    },
    //用户授权界面
    auth() {
      /*       // 如果本地没有 token ，那就跳转到授权页面，发起请求换取 token
            if (!wx.getStorageSync('token')) {
              // 跳转到授权页面
              wx.navigateTo({ url: '/pages/auth/main' });
            } else {
              wx.navigateTo({ url: '/pages/accPay/main' });
            } */
      //生成订单 下面data是我们需要发送的参数数据
      let data = {
        order_price: this.allPrice,
        consignee_addr:this.address.userAddress ,
        goods:[]
      }
      for(let key in this.cartList){
        data.goods.push({
          goods_id:this.cartList[key].goods_id,
          goods_number:this.cartList[key].count,
          goods_price:this.cartList[key].goods_price
        })
      }
      orderCreate(data)
        .then(res => {
          // console.log(res)
          const {order_number} = res.data.message
          wx.setStorageSync('carts', this.cartList)
          this.cartList = wx.getStorageSync('carts');
          //携带订单号跳转到订单确认支付页面
          wx.navigateTo({ url: `/pages/accPay/main?order_number=${order_number}` });
        })
    }

  },
  onLoad() {
    //页面加载的时候获取我们本地存储的用户信息 我们进来就不用再是新增用户了
    // 我们一开始是没有address这个键的 我们可以先给this.address先设置一个空对象 不然会一直不存在
    this.address = wx.getStorageSync('address') || {};
  },
  onShow() {
    //页面加载获取本地的加入购物车的数据
    this.cartList = wx.getStorageSync('carts')
  },
  computed: {
    allPrice() {
      //页面加载的时候先获取总数和总价
      this.allCount = 0
      let allPrice = 0
      for (let key in this.cartList) {
        if (this.cartList[key].state) {
          allPrice += this.cartList[key].count * this.cartList[key].goods_price
          this.allCount++
        }
      }
      //通过keys我们可以返回一个我们this.cartList对象所有的键组成的数组我们可以获取 数组的长度
      this.cartLength = Object.keys(this.cartList).length
      return allPrice
    }
  }
}
</script>

<style lang='scss'>
.cart-top {
  font-size: 32rpx;
  padding: 0 25rpx;
  border-bottom: 20rpx solid #ccc;
  .addConsignee {
    text-align: center;
    padding: 40rpx 0;
    font-size: 32rpx;
    &::after {
      content: "+";
    }
  }
  .cart-top-content {
    display: flex;
    justify-content: space-between;
    line-height: 86rpx;
    .cart-consignee {
    }
    .cart-phone {
      &::after {
        content: ">";
        padding-left: 50rpx;
        font-size: 40rpx;
        color: #666;
      }
    }
  }
  .address {
    margin-bottom: 50rpx;
  }
}
.cart-content {
  .cart-content-title {
    padding: 30rpx;
    font-size: 30rpx;
    border-bottom: 1px solid #999;
  }
  .cart-content-item {
    display: flex;
    .item-change {
      width: 100rpx;
      display: flex;
      justify-content: center;
      align-items: center;
      font-size: 30rpx;
    }
    .item-content {
      flex: 1;
      display: flex;
      padding: 20rpx 0;
      border-bottom: 1px solid #ddd;
      .item-img {
        width: 180rpx;
        height: 200rpx;
        img {
          width: 100%;
          height: 100%;
          display: block;
        }
      }
      .item-desc {
        flex: 1;
        display: flex;
        width: 100%;
        flex-direction: column;
        justify-content: space-between;
        padding: 0 20rpx;
        font-size: 30rpx;
        .item-price {
          color: red;
        }
        view {
          &:nth-of-type(2) {
            display: flex;
            justify-content: space-between;
          }
          &:nth-of-type(2) {
            .addCount {
              display: inline-block;
              width: 60rpx;
              height: 50rpx;
              text-align: center;
              line-height: 50rpx;
              border-radius: 5px;
              border: 2px solid #666;
            }
            .count {
              padding: 0 35rpx;
            }
          }
        }
      }
    }
  }
}
.icon-xuanze-fill {
  color: #ff2d4a;
}
.cart-footer {
  position: fixed;
  display: flex;
  left: 0;
  bottom: 0;
  width: 100%;
  background-color: #fff;
  > view {
    flex: 1;
    &:nth-of-type(1),
    &:nth-of-type(3) {
      display: flex;
      justify-content: center;
      align-items: center;
      font-size: 32rpx;
    }
    &:nth-of-type(1) {
      span {
        margin-right: 20rpx;
      }
    }
    &:nth-of-type(3) {
      background-color: #ff2d4a;
      color: #fff;
    }
    &:nth-of-type(2) {
      display: flex;
      flex-direction: column;
      justify-content: space-around;
      align-items: flex-start;
      .count-allPrice {
        font-size: 32rpx;
        span {
          color: #ff2d4a;
        }
      }
      .sportPrice {
        font-size: 28rpx;
        color: #bbb;
      }
    }
  }
}
</style>


